<?php declare(strict_types=1);

/**
 * @author      guosir
 * @copyright   2023-2025 owner
 **/

namespace Srv\Apps\Apis\Banner\Ctl;

use Srv\Apps\Apis\Common\Ctl\StorageCtl;
use Srv\Apps\Apis\Common\DefCtl\DefStorageCategoryCtl;
use Srv\Apps\Apis\Skit\Ctl\SkitInfoCtl;
use Srv\Apps\Apis\Skit\Ctl\SkitSeriesCtl;
use Srv\Apps\Proto\DTO\Banner\BannerWebAddDTO;
use Srv\Apps\Proto\DTO\Banner\BannerWebEditDTO;
use Srv\Apps\Proto\DTO\Banner\BannerWebListDTO;
use Srv\Apps\Proto\Enum\BannerOpenTypeWebEnum;
use Srv\Apps\Proto\Enum\YesOrNoEnum;
use Srv\Apps\Proto\VO\Banner\BannerWebListVO;
use Srv\Apps\Proto\VO\Banner\BannerWebVO;
use Srv\Apps\Proto\VO\Skit\SkitInfoVO;
use Srv\Apps\Proto\VO\Skit\SkitSeriesVO;
use Srv\Libs\Common\CommArray;
use Srv\Libs\Common\CommTime;
use Srv\Libs\Frame\AuthData;
use Srv\Libs\Frame\ControllerAbstract;
use Srv\Libs\Frame\Page;
use Srv\Libs\Storage\DataMysql;

final class BannerWebCtl extends ControllerAbstract
{
    private ?DataMysql $DbAuto              = null;     // DB-Write

    /**
     * @return static
     * tag
     */
    final public static function tag():self
    {
        $thisObject                         = self::tagGet();
        if($thisObject instanceof self){
            $thisObject->DbAuto             = self::getDbAuto();
        }
        return $thisObject;
    }

    /**
     * @param int $bawrId
     * @return array
     * getBannerWebSrc
     */
    public function getBannerWebSrc(int $bawrId):array
    {
        if($bawrId < 1) return [];
        $isFail         = false;
        $info           = $this->DbAuto->getDataOne('SELECT bawr_id, bawr_title, bawr_image, bawr_image_mobile, bawr_url, bawr_open_type, skio_id, skss_id, bawr_status, bawr_sort, bawr_create_time, bawr_update_time FROM '.$this->DbAuto->getTableNameAll('banner_web_record').' WHERE bawr_id='.$bawrId.' AND bawr_delete=0', $isFail);
        if($isFail || !isset($info['bawr_id'])) return [];
        return $info;
    }

    /**
     * @param Page $Page
     * @param array $whereData
     * @return BannerWebListVO|null
     * getBannerWebList
     */
    public function getBannerWebList(Page $Page, array $whereData): ?BannerWebListVO
    {
        $limitString        = $Page->getLimitString();
        $whereString        = ' WHERE bawr_delete=0 ';
        // 检索条件
        if(count($whereData) > 0)foreach ($whereData as $key => $val){
            switch ($key){
                case BannerWebListDTO::_bawrId:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'bawr_id='. intval($val);
                    break;
                case BannerWebListDTO::_title:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'bawr_title LIKE \'%'.$this->DbAuto->getRealEscapeString($val).'%\'';
                    break;
                case BannerWebListDTO::_status:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'bawr_status='. intval($val);
                    break;
                case BannerWebListDTO::_openType:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'bawr_open_type='. intval($val);
                    break;
                case BannerWebListDTO::_skioId:
                    $whereString    .= (strlen($whereString)>0?' AND ':'').'skio_id='. intval($val);
                    break;
            }
        }
        $isFail             = false;
        $sql                = 'SELECT SQL_CALC_FOUND_ROWS bawr_id, bawr_title, bawr_image, bawr_image_mobile, bawr_url, bawr_open_type, skio_id, skss_id, bawr_status, bawr_sort, bawr_create_time, bawr_update_time FROM '.$this->DbAuto->getTableNameAll('banner_web_record').$whereString.' ORDER BY bawr_id DESC '.$limitString;
        $list               = $this->DbAuto->getData($sql, $isFail);
        $totalNum           = $this->DbAuto->getDataInt('SELECT FOUND_ROWS() as num', 'num');
        if($isFail) return null;
        $BannerWebVOList    = [];
        if(CommArray::isForeach($list)){
            $skioIdList         = array_map('intval', array_column($list, 'skio_id'));
            $SkitInfoVOList     = SkitInfoCtl::tag()->getSkitInfoBatch($skioIdList);
            $skssIdList         = array_map('intval', array_column($list, 'skss_id'));
            $SkitSeriesVOList   = SkitSeriesCtl::tag()->getSkitSeriesInfoBatch($skssIdList);
            foreach($list as $item){
                $bawrIdItem         = intval($item['bawr_id']);
                if($bawrIdItem < 1) continue;
                $BannerWebVO        = $this->getBannerWebVO($item);
                if(!($BannerWebVO instanceof BannerWebVO)) continue;
                $SkitInfoVO         = $SkitInfoVOList[intval($item['skio_id'])]??null;
                if($SkitInfoVO instanceof SkitInfoVO) $BannerWebVO->setSkitInfo($SkitInfoVO);
                $SkitSeriesVO       = $SkitSeriesVOList[intval($item['skss_id'])]??null;
                if($SkitSeriesVO instanceof SkitSeriesVO) $BannerWebVO->setSeries($SkitSeriesVO);
                $BannerWebVOList[]  = $BannerWebVO;
            }
        }
        $BannerWebListVO        = new BannerWebListVO();
        $BannerWebListVO->setList($BannerWebVOList);
        $BannerWebListVO->setPage($Page->getPageVO($totalNum));
        return $BannerWebListVO;
    }

    /**
     * @param int $bawrId
     * @return BannerWebVO|null
     * getBannerWebInfo
     */
    public function getBannerWebInfo(int $bawrId):?BannerWebVO
    {
        $bannerRecord   = $this->getBannerWebSrc($bawrId);
        if(!isset($bannerRecord['bawr_id'])) return null;
        return $this->getBannerWebVO($bannerRecord);
    }

    /**
     * @param array $bannerRecord
     * @return BannerWebVO|null
     * getBannerWebVO
     */
    public function getBannerWebVO(array $bannerRecord): ?BannerWebVO
    {
        $bawrId             = intval($bannerRecord['bawr_id']??0);
        if($bawrId < 1) return null;
        $BannerWebVO        = new BannerWebVO();
        $BannerWebVO->setBawrId($bawrId);
        $BannerWebVO->setTitle($bannerRecord['bawr_title']);
        $BannerWebVO->setImageUrl(StorageCtl::tag()->getStorageUrl(trim($bannerRecord['bawr_image']), true));
        $BannerWebVO->setImageMobileUrl(StorageCtl::tag()->getStorageUrl(trim($bannerRecord['bawr_image_mobile']), true));
        $BannerWebVO->setUrl($bannerRecord['bawr_url']);
        $BannerWebVO->setStatus(YesOrNoEnum::parseValue($bannerRecord['bawr_status']));
        $BannerWebVO->setOpenType(BannerOpenTypeWebEnum::parseValue($bannerRecord['bawr_open_type']));
        $BannerWebVO->setSort(intval($bannerRecord['bawr_sort']));
        $BannerWebVO->setCreateTime(intval($bannerRecord['bawr_create_time']));
        $BannerWebVO->setUpdateTime(intval($bannerRecord['bawr_update_time']));
        return $BannerWebVO;
    }

    /**
     * @param array $setData
     * @return int
     * bannerWebAdd
     */
    public function bannerWebAdd(array $setData):int
    {
        if(count($setData) < 1) return 0;
        $currTime   = CommTime::getTimeStamp();
        $setString  = '';
        $admUserId  = AuthData::getLoginUserId();
        $dsacId     = DefStorageCategoryCtl::tag()->getIdByKey(DefStorageCategoryCtl::KEY_BANNER_WEB);
        foreach ($setData as $key => $val){
            switch ($key){
                case BannerWebAddDTO::_title:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_title=\''.$this->DbAuto->getRealEscapeString($val) .'\'';
                    break;
                case BannerWebAddDTO::_imageKey:
                    if($dsacId < 1) return 0;
                    $saveUrl        = StorageCtl::tag()->getStorageUrlRecord($admUserId, $dsacId, $val);
                    if(strlen($saveUrl) < 1) return 0;
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_image=\''.$this->DbAuto->getRealEscapeString($saveUrl) .'\'';
                    break;
                case BannerWebAddDTO::_imageMobileKey:
                    if($dsacId < 1) return 0;
                    $saveUrl        = StorageCtl::tag()->getStorageUrlRecord($admUserId, $dsacId, $val);
                    if(strlen($saveUrl) < 1) return 0;
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_image_mobile=\''.$this->DbAuto->getRealEscapeString($saveUrl) .'\'';
                    break;
                case BannerWebAddDTO::_url:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_url=\''.$this->DbAuto->getRealEscapeString($val) .'\'';
                    break;
                case BannerWebAddDTO::_openType:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_open_type='.intval($val);
                    break;
                case BannerWebAddDTO::_skioId:
                    $skioId         = intval($val);
                    if($skioId > 0){
                        $skitInfoSrc= SkitInfoCtl::tag()->getSkitInfoSrc($skioId);
                        if(!isset($skitInfoSrc['skio_id'])) return 0;
                    }
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'skio_id='.$skioId;
                    break;
                case BannerWebAddDTO::_skssId:
                    $skssId         = intval($val);
                    if($skssId > 0){
                        $seriesSrc  = SkitSeriesCtl::tag()->getSkitSeriesSrc($skssId);
                        if(!isset($seriesSrc['skss_id'])) return 0;
                    }
                    $setString  .= (strlen($setString) > 0 ? ', ' : '') . 'skss_id='.$skssId;
                    break;
                case BannerWebAddDTO::_status:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_status='.intval($val);
                    break;
                case BannerWebAddDTO::_sort:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_sort='.intval($val);
                    break;
            }
        }
        if(strlen($setString) < 1) return 0;
        $isFail     = false;
        $sql        = 'INSERT INTO '.$this->DbAuto->getTableNameAll('banner_web_record').' SET '.$setString.', bawr_create_time='.$currTime.', bawr_update_time='.$currTime;
        $bawrId     = $this->DbAuto->getDataId($sql, $isFail);
        if($isFail || $bawrId < 1) return 0;
        return $bawrId;
    }

    /**
     * @param int $bawrId
     * @param array $setData
     * @return bool
     * bannerWebEdit
     */
    public function bannerWebEdit(int $bawrId, array $setData):bool
    {
        if($bawrId < 1 || count($setData) < 1) return false;
        $currTime       = CommTime::getTimeStamp();
        $admUserId      = AuthData::getLoginUserId();
        $setString      = '';
        $dsacId         = DefStorageCategoryCtl::tag()->getIdByKey(DefStorageCategoryCtl::KEY_BANNER_WEB);
        foreach ($setData as $key => $val){
            switch ($key){
                case BannerWebEditDTO::_title:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_title=\''.$this->DbAuto->getRealEscapeString($val) .'\'';
                    break;
                case BannerWebEditDTO::_imageKey:
                    if($dsacId < 1) return false;
                    $saveUrl        = StorageCtl::tag()->getStorageUrlRecord($admUserId, $dsacId, $val);
                    if(strlen($saveUrl) < 1) return false;
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_image=\''.$this->DbAuto->getRealEscapeString($saveUrl) .'\'';
                    break;
                case BannerWebEditDTO::_imageMobileKey:
                    if($dsacId < 1) return false;
                    $saveUrl        = StorageCtl::tag()->getStorageUrlRecord($admUserId, $dsacId, $val);
                    if(strlen($saveUrl) < 1) return false;
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_image_mobile=\''.$this->DbAuto->getRealEscapeString($saveUrl) .'\'';
                    break;
                case BannerWebEditDTO::_url:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_url=\''.$this->DbAuto->getRealEscapeString($val) .'\'';
                    break;
                case BannerWebEditDTO::_openType:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_open_type='.intval($val);
                    break;
                case BannerWebEditDTO::_skioId:
                    $skioId         = intval($val);
                    if($skioId > 0){
                        $skitInfoSrc= SkitInfoCtl::tag()->getSkitInfoSrc($skioId);
                        if(!isset($skitInfoSrc['skio_id'])) return false;
                    }
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'skio_id='.$skioId;
                    break;
                case BannerWebEditDTO::_skssId:
                    $skssId         = intval($val);
                    if($skssId > 0){
                        $seriesSrc  = SkitSeriesCtl::tag()->getSkitSeriesSrc($skssId);
                        if(!isset($seriesSrc['skss_id'])) return false;
                    }
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'skss_id='.$skssId;
                    break;
                case BannerWebEditDTO::_status:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_status='.intval($val);
                    break;
                case BannerWebEditDTO::_sort:
                    $setString      .= (strlen($setString) > 0 ? ', ' : '') . 'bawr_sort='.intval($val);
                    break;
            }
        }
        if(strlen($setString) < 1) return false;
        $isFail     = false;
        $sql        = 'UPDATE '.$this->DbAuto->getTableNameAll('banner_web_record').' SET '.$setString.', bawr_update_time='.$currTime.' WHERE bawr_id='.$bawrId.' AND bawr_delete=0';
        $this->DbAuto->getDataNum($sql, $isFail);
        if($isFail) return false;
        return true;
    }
}